import axios from 'axios';
import { Modal } from 'ant-design-vue';
// spin 是 iview 的一个显示加载中的组件，如果需要启用，可切到ant对应的组件即可
// import { Spin } from 'iview'
class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    };
    return config;
  }
  distroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          // Spin.show() // 不建议开启，因为界面不友好
        }
        this.queue[url] = true;
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.distroy(url);
        const { data, status } = res;
        if (res.status === 204 || res.status === 200) {
          return Promise.resolve({ data, status });
        } else {
          // 如果api请求出错，全局提示弹出窗
          Modal.error({
            title: '操作失败',
            content: res.data.message,
            okText: '确定'
          });
          return Promise.reject(res.data.message);
        }
      },
      error => {
        this.distroy(url);
        return Promise.reject(error);
      }
    );
  }
  request(options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    // 统一将 page 减1
    if (options.params && options.params.page) {
      options.params = Object.assign(options.params, {
        page: options.params.page - 1
      });
    }
    return instance(options);
  }
}
export default HttpRequest;
